#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>

#define INPUT 0
#define OUTPUT 1

int main(){
	int file_descriptors[2];
	pid_t pid1;
	pid_t pid2;
	char buf[256];
	int read_count;
	int result;
	char *msg1 = "Child 1 is sending a message!\n";
	char *msg2 = "Child 2 is sending a message!\n";
	
	result = pipe(file_descriptors);
	if(result == -1){
		perror("Failed in calling pipe");
		exit(1);
	}
	
	pid1 = fork();
	if (pid1 < 0){
		perror("Failed in calling fork");
		exit(1);
	} else if (pid1 == 0){	//child 1
		//printf("Child 1 is sending a message!\n");
		//sleep(3);
		close(file_descriptors[INPUT]);
		result = write(file_descriptors[OUTPUT],msg1, strlen(msg1));
		if (result == -1){
			perror("In Child1, failed to write to pipe");
			exit(1);
		}		
		close(file_descriptors[OUTPUT]);
		exit(0);
	} else{	//parent
		pid2 = fork();
		if (pid2 < 0){
			perror("Failed in calling fork");
			exit(1);
		} else if (pid2 == 0){	//child 2
			//sleep(3);
			close(file_descriptors[INPUT]);
			result = write(file_descriptors[OUTPUT],msg2, strlen(msg2));
			if (result == -1){
				perror("In Child2, failed to write to pipe");
				exit(1);
			}		
			close(file_descriptors[OUTPUT]);
			exit(0);
		}
		sleep(3);
		close(file_descriptors[OUTPUT]);
		
		
		read_count = read(file_descriptors[INPUT], buf, sizeof(buf));
		if (read_count == -1){
			perror("In parent, failed to read from pipe");
			exit(1);
		}else if (read_count == 0){
			printf("In parent, 0 byte read from pipe.\n");
		}else{
			buf[read_count] = '\0';
			printf("%s",buf);
		}
		close(file_descriptors[INPUT]);
	}
	
	return (EXIT_SUCCESS);
}
